<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import ColorPicker from './ColorPicker.vue'
import { generateImageAPI, checkTaskStatusAPI } from '@/services/app'
import type { GenerateTask } from '@/types/app'
import { baseurl } from '@/utils/http'

const props = defineProps({
  title: String,
  description: String,
  workflowParams: Object,
  workflowId: String,
  placeholderImage: String
})
const emit = defineEmits(['generation-success'])

const formData = ref<any>({})
const generating = ref(false)
const generatedImage = ref('')
const processingStatus = ref('')
const paramsLoaded = computed(() => !!props.workflowParams && Object.keys(props.workflowParams).length > 0)

// 获取当前应该显示的图片
const currentPreviewImage = computed(() => {
  // 如果有生成的图片，优先显示生成的图片
  if (generatedImage.value) {
    return generatedImage.value
  }
  
  // 查找是否有上传的图片
  const uploadedImage = Object.values(formData.value).find((value: any) => 
    typeof value === 'string' && (value.startsWith('http') || value.startsWith('blob:') || value.startsWith('file://'))
  )
  
  if (uploadedImage) {
    return uploadedImage as string
  }
  
  // 否则显示占位符图片
  return props.placeholderImage || ''
})

// 上传图片
const handleChooseImage = async (key: string) => {
  uni.chooseImage({
    count: 1,
    success: (res: any) => {
      if (res.tempFilePaths && res.tempFilePaths.length > 0) {
        formData.value[key] = res.tempFilePaths[0] // 预览
        formData.value[`${key}_file`] = res.tempFilePaths[0] // 真正上传
        generatedImage.value = '' // 重点：清空生成图片，优先显示新上传的图片
      }
    }
  })
}

const generateTaskId = ref<string>()
const generateImageCall = async (data: any) => {
  const res = await generateImageAPI(data)
  generateTaskId.value = res.taskId
}

const generateTask = ref<GenerateTask>()
const checkTaskStatusCall = async (taskId: string) => {
  const res = await checkTaskStatusAPI(taskId)
  generateTask.value = res.result
}

const waitForTaskComplete = async (taskId: string) => {
  let cancelFlag = false
  generating.value = true
  try {
    while (!cancelFlag) {
      await checkTaskStatusCall(taskId)
      const task = generateTask.value
      if (task?.status === 'FAILED') {
        throw new Error(task.errorMsg || '任务执行失败')
      }
      if (task?.status === 'COMPLETED') {
        if (task.imagePath) {
          // #ifdef H5
          generatedImage.value = baseurl + task.imagePath
          // #endif
          // #ifndef H5
          // 微信小程序端拼接 baseurl
          generatedImage.value = baseurl + task.imagePath
          // #endif
          emit('generation-success')
        } else {
          throw new Error('未找到生成的图像')
        }
        break
      }
      await new Promise(resolve => setTimeout(resolve, 1000))
    }
  } catch (error: any) {
    uni.showToast({ title: error.message || '生成失败', icon: 'none' })
    throw error
  } finally {
    generating.value = false
  }
}

// 生成图片
const generateImage = async () => {
  if (!paramsLoaded.value) {
    uni.showToast({ title: '请先配置参数', icon: 'none' })
    return
  }
  generating.value = true
  generatedImage.value = ''
  processingStatus.value = ''
  uni.pageScrollTo({ scrollTop: 0, duration: 300 })

  // 构建请求数据
  const requestData: any = {}
  Object.entries(formData.value).forEach(([key, value]) => {
    requestData[key] = value
  })
  requestData.workflowId = props.workflowId || ''
  // 如果有复杂参数对象
  // requestData.params = { ... }
  console.log('requestData:',requestData)
  try {
    await generateImageCall(requestData)
    if (!generateTaskId.value) {
      throw new Error('生成任务创建失败')
    }
    const taskId = generateTaskId.value
    await waitForTaskComplete(taskId)
    uni.showToast({ title: '生成成功', icon: 'success' })
  } catch (error: any) {
    generating.value = false
    uni.showToast({ title: error.message || '生成失败', icon: 'none' })
  }
}

// 监听参数变化，设置默认值
watch(() => props.workflowParams, (params) => {
  if (params) {
    Object.entries(params).forEach(([key, param]: any) => {
      formData.value[key] = param.default || ''
    })
  }
}, { immediate: true })

const handleColorChange = (key: string, color: string) => {
  formData.value[key] = color;
  console.log('颜色已更改:', color);
};

// 预览图片
const previewImage = (imageUrl: string) => {
  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl
  })
}
</script>

<template>
  <view class="app-page">
    <view class="header">
      <!-- <text class="title">{{ props.title }}</text> -->
      <text class="desc">{{ props.description }}</text>
    </view>
    <view class="content">
      <!-- 预览区域 -->
      <view class="preview-section">
        <view class="preview-container">
          <!-- 空状态或上传图片预览 -->
          <view v-if="!generatedImage && !generating" class="preview-placeholder">
            <view class="placeholder-content">
              <image 
                :src="currentPreviewImage" 
                class="placeholder-image" 
                mode="aspectFit"
                @click="currentPreviewImage !== (props.placeholderImage || '') ? previewImage(currentPreviewImage) : null"
              />
              <text class="placeholder-text">
                {{ currentPreviewImage === (props.placeholderImage || '') ? '上传素材并配置参数后点击生成查看效果' : '点击图片可放大预览，配置参数后点击生成' }}
              </text>
            </view>
          </view>
          
          <!-- 生成中状态 -->
          <view v-else-if="generating" class="processing-preview">
            <view class="status-tag">正在生成图像...</view>
            <text class="processing-text">AI正在生成中...</text>
          </view>
          
          <!-- 生成结果 -->
          <view v-else class="result-preview">
            <view class="preview-image-container">
              <image 
                :src="generatedImage" 
                class="preview-image"
                mode="aspectFit"
                @click="previewImage(generatedImage)"
              />
            </view>
            <view class="image-meta">
              <text class="meta-text">生成时间：{{ new Date().toLocaleString('zh-CN') }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 参数配置区域 -->
      <view class="params-section" v-if="paramsLoaded">
        <view v-for="(param, key) in props.workflowParams" :key="key" class="param-item">
          <template v-if="param.type === 'image'">
            <button type="primary" @click="handleChooseImage(key)">上传图片</button>
          </template>
          <template v-else-if="param.type === 'colorPicker'">
            <ColorPicker
              :preset-colors="['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff', '#ff00ff']"
              :disabled="false"
              :show-alpha="false"
              v-model="formData[key]"
              @change="(color: string) => handleColorChange(key, color)"
              />
            <text class="demo-value">选中的颜色: {{ formData[key] }}</text>
          </template>
          <template v-else-if="param.type === 'number'">
            <input type="number" v-model="formData[key]" class="param-input" />
          </template>
          <template v-else-if="param.type === 'select'">
            <picker :range="param.options.map((o: any) => o.label)" @change="(e: any) => formData[key] = param.options[e.detail.value].value">
              <view class="picker-view">{{ param.options.find((o: any) => o.value === formData[key])?.label || '请选择' }}</view>
            </picker>
          </template>
          <template v-else>
            <input type="text" v-model="formData[key]" class="param-input" />
          </template>
          <view class="param-label">{{ param.label }}</view>
        </view>
      </view>
      <!-- 生成按钮 -->
      <view class="generate-btn-section">
        <button type="primary" :loading="generating" @click="generateImage" :disabled="generating || !paramsLoaded">生成图像</button>
      </view>
    </view>
  </view>
</template>

<style scoped>
.app-page {
  padding: 24rpx;
}
.header {
  text-align: center;
  margin-bottom: 32rpx;
}
.title {
  font-size: 40rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 12rpx;
}
.desc {
  color: #666;
  font-size: 28rpx;
}
.content {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  padding: 24rpx;
}
.preview-section {
  width: 100%;
  height: 400px;
  margin-bottom: 20rpx;
}
.preview-container {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 16rpx;
  overflow: hidden;
}
.preview-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.placeholder-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 100%;
  height: 100%;
  padding: 0px;
}
.placeholder-image {
  width: 100%;
  height: 100%;
  border-radius: 20px;
  margin-bottom: 0px;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.01);
}
.placeholder-text {
  color: #606266;
  font-size: 28rpx;
  line-height: 1.5;
}
.processing-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.status-tag {
  background-color: #409eff;
  color: white;
  padding: 16rpx 32rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  margin-bottom: 20rpx;
}
.processing-text {
  color: #606266;
  font-size: 28rpx;
}
.result-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.preview-image-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
}
.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.1);
}
.image-meta {
  padding: 20rpx;
  border-top: 1rpx solid #e4e7ed;
}
.meta-text {
  color: #606266;
  font-size: 24rpx;
}
.params-section {
  margin-bottom: 32rpx;
}
.param-item {
  margin-bottom: 24rpx;
}
.param-label {
  color: #888;
  font-size: 24rpx;
  margin-top: 8rpx;
}
.param-input {
  width: 100%;
  height: 60rpx;
  font-size: 28rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 0 16rpx;
  margin-top: 8rpx;
}
.param-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-top: 8rpx;
}
.picker-view {
  padding: 16rpx;
  background: #f0f0f0;
  border-radius: 8rpx;
  margin-top: 8rpx;
  color: #333;
}
.generate-btn-section {
  display: flex;
  justify-content: center;
  margin-top: 32rpx;
}
</style>
